import {reactive, ref} from 'vue';

export default function (proxy) {
  const hasPagination = ref(true);
  const table = reactive({
    isLoading: false,
    isSingleExpanded: true,
    columns: [],
    data: [],
    defaultSort: {prop: 'createTime', order: 'descending'},
    sortOrders: ['descending', 'ascending'],
    orderField: '',
    orderBy: 'DESC',
    selection: [],
    selectParamProp: 'id',
    selectParams: [],
    rowKeyProps: ['id'],
    expandRowKeys: [],
    configurableColumns: [],
    configurableVisibleColumns: []
  });
  const pagination = reactive({
    size: 30,
    current: 1,
    sizes: [30, 70, 100, 150],
    total: 0
  });

  // 设置表格动态列可见
  const handleVisibleColumnsChange = props => {
    table.configurableVisibleColumns = props;
  };
  // 拿取表格数据后回到顶部
  const scrollToTop = () => {
    document.querySelector('.table-container .el-table__body-wrapper').scrollTo(0, 0);
  };
  // 拿到表格对象
  const getBaseTableComponent = () => proxy.$refs.baseTableContainer.$refs.baseTable;
  // 设置表格数据
  const setTableData = async (module, apiName, params) => {
    table.isLoading = true;
    const res = await proxy.$api[module][apiName](params);
    table.isLoading = false;
    if (!!res && res.status === 200) {
      table.data = (res.data || {data: []}).data;
      pagination.total = (res.data || {total: []}).total;
    } else {
      proxy.$message.error(res.message);
    }
  };
  // 分页事件：val - 值（当前页或者分页大小）、type - 事件类型，size：改变分页大小，current：改变当前页
  const handlePaging = (val, type = 'current') => {
    if (type === 'size') {
      pagination.size = val;
      pagination.current = 1;
    } else {
      pagination.current = val;
    }
    proxy.getTableData();
    scrollToTop();
  };
  // 表格排序
  const handleSortChange = (prop, order) => {
    setTableSortValue({prop, order});
    pagination.current = 1;
    proxy.getTableData();
    scrollToTop();
  };
  // 设置表格排序值
  const setTableSortValue = ({prop, order}) => {
    table.orderField = prop;
    table.orderBy = order === 'ascending' ? 'ASC' : 'DESC';
  };
  // 搜索、新增、删除 表格数据时调用
  const refreshTableData = obj => {
    pagination.current = 1;
    proxy.getTableData();
    scrollToTop();
  };
  // 表格勾选
  const handleSelectionChange = row => {
    table.selection = row;
    table.selectParams = getSelectParams();
  };
  // 拿到表格勾选参数
  const getSelectParams = (paramKey = table.selectParamProp, selection = table.selection) => {
    if (!paramKey || !/string|object/.test(typeof paramKey)) return false;
    const params = selection.map(item => {
      if (typeof paramKey === 'string') return item[paramKey];
      let temp = [];
      if (paramKey instanceof Array) {
        // 如果是数组 如：['ip', 'id']
        for (const key of paramKey) temp.push(item[key]);
      } else {
        // 如果是对象 如：{dataId: 'id', dataInId: 'inId'}
        temp = {};
        for (const key in paramKey) {
          temp[key] = item[paramKey[key]];
        }
      }
      return temp;
    });
    return params;
  };
  // 获取表格行键值，一般在有扩展行的时候才用
  const getRowKey = (row, props = table.rowKeyProps) => {
    return props.reduce((str, key) => str + row[key], '');
  };
  // 表格行展开
  const handleExpandChange = expandRows => {
    table.expandRowKeys = expandRows.map(row => table.getRowKey(row));
  };
  // 拿到行展开信息：key、是否已展开、在expandRowKeys中的序号
  const getExpandRowInfo = row => {
    const rowKey = table.getRowKey(row);
    const index = table.expandRowKeys.indexOf(rowKey);
    const isExpanded = index !== -1;
    return {rowKey, isExpanded, index};
  };
  // 手动触发行展开-几乎用不到
  const manualTriggerExpandRow = row => {
    const {rowKey, isExpanded, index} = getExpandRowInfo(row);
    const args = isExpanded ? [index, 1] : [0, table.isSingleExpanded ? table.expandRowKeys.length : 0, rowKey];
    table.expandRowKeys.splice(...args);
  };
  // 切换行展开
  const toggleRowExpansion = row => {
    // manualTriggerExpandRow(row);
    getBaseTableComponent().toggleRowExpansion(row);
    const {isExpanded: isNeedExpand} = getExpandRowInfo(row);
    if (isNeedExpand) {
      if (!row.detail) row.detail = {isLoading: true, data: {}};
      proxy.getExpandRowDetail(row);
    }
  };
  // 设置行展开数据
  const setExpandRowDetail = async (row, module, apiName, params) => {
    row.detail.isLoading = true;
    const res = await proxy.$api[module][apiName](params);
    row.detail.isLoading = false;
    if (res.status === 200) row.detail.data = res.data;
  };
  // 根据需要获取的表格查询参数类型，获取表格查询参数
  const getTableRequestParams = (type = ['page', 'sort'], otherParams = {}) => {
    if (!(type instanceof Array)) return {...otherParams};
    const params = {};
    if (type.includes('page')) {
      Object.assign(params, {
        currentPage: pagination.current,
        pageSize: pagination.size
      });
    }
    if (type.includes('sort')) {
      if (!table.orderField) setTableSortValue(table.defaultSort);
      Object.assign(params, {
        orderField: table.orderField,
        orderBy: table.orderBy
      });
    }
    return Object.assign(params, otherParams);
  };
  // 行序号
  const rowIndex = index => {
    return (hasPagination.value ? (pagination.current - 1) * pagination.size : 0) + index + 1;
  };

  table.getRowKey = getRowKey;
  return {
    hasPagination,
    table,
    pagination,
    handleVisibleColumnsChange,
    getBaseTableComponent,
    setTableData,
    refreshTableData,
    handlePaging,
    handleSortChange,
    handleSelectionChange,
    handleExpandChange,
    getSelectParams,
    manualTriggerExpandRow,
    toggleRowExpansion,
    setExpandRowDetail,
    getTableRequestParams,
    rowIndex
  };
}
